//
//  FengSceneControllerHandle.m
//  FengSiriDemo
//
//  Created by Feng on 2021/7/27.
//

#define ARG_Akeeta_AppKey       @"appKey"
#define ARG_Akeeta_AppSecret    @"appSecret"
#define ARG_Akeeta_Sign         @"sign"
#define ARG_Akeeta_AccessToken  @"accessToken"

#import "FengSceneControllerHandle.h"
#import "FengAppExtensionHelper.h"
#import "SceneControlIntent.h"

#import <MD5Digest/NSString+MD5.h>
#import "Akeeta_NetWorking.h"

@implementation FengSceneControllerHandle

- (void)handleSceneControl:(SceneControlIntent *)intent completion:(void (^)(SceneControlIntentResponse * _Nonnull))completion API_AVAILABLE(ios(12.0)) {

    NSString *sceneId = intent.sceneId;
    NSLog(@"%@", [FengAppExtensionHelper getSiriData]);

    //执行场景
    __weak typeof(self)weakSelf = self;
    [self executeSceneWithSceneId:sceneId success:^(id response) {
        [weakSelf handlerCompeletionWithCode:(SceneControlIntentResponseCodeSuccess) errorMsg:@"场景执行成功" completion:completion];
    } failure:^(NSError *error) {
        [weakSelf handlerCompeletionWithCode:(SceneControlIntentResponseCodeSuccess) errorMsg:error.description completion:completion];
    }];
}

- (void)handlerCompeletionWithCode:(SceneControlIntentResponseCode)code errorMsg:(NSString *)errorMsg completion:(void (^)(SceneControlIntentResponse * _Nonnull))completion API_AVAILABLE(ios(12.0)) {

    NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([SceneControlIntent class])];
    SceneControlIntentResponse *response = [[SceneControlIntentResponse alloc] initWithCode:code userActivity:userActivity];
    response.errorMsg = errorMsg;  //自定义提示语
    completion(response);
}

#pragma mark --执行场景
- (void)executeSceneWithSceneId:(NSString *)sceneId
                        success:(void (^)(id response))successBlock
                        failure:(void (^)(NSError *error))failureBlock  {
    NSLog(@"__%s %d 执行场景",__func__,__LINE__);

    NSDictionary *siriData = [FengAppExtensionHelper getSiriData];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:sceneId forKey:@"sceneId"];
    NSDictionary *encodeDic = [self akeetaParamEncodeWithParam:dic
                                                        appKey:siriData[@"appKey"]
                                                     appsecret:siriData[@"appSecret"]
                                                         token:siriData[@"accessToken"]];
    
    NSLog(@"encodeDic: %@", encodeDic);
    NSString *url = [NSString stringWithFormat:@"%@api/oem_app/ble_mesh_scene/execute", siriData[@"baseUrl"]];
    [Akeeta_NetWorking postWithPath:url params:encodeDic clientToken:@"" success:^(id  _Nonnull responseObject) {
        NSLog(@"responseObject: %@", responseObject);

        id code = responseObject[@"code"];
        if ([code integerValue] == 200) {
            if (successBlock) {
                successBlock(responseObject[@"object"]?:responseObject);
            }
        }
        else{
            if (failureBlock) {
                failureBlock([NSError errorWithDomain:responseObject[@"msg"] code:[code intValue] userInfo:responseObject]);
            }
        }
    } failure:^(NSError * _Nonnull error) {

        NSLog(@"error: %@", error);

        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

#pragma --akeeta param encode
- (NSDictionary *)akeetaParamEncodeWithParam:(NSDictionary *)param appKey:(NSString *)appKey appsecret:(NSString *)appsecret token:(NSString *)token {

    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:param];
    [dic setValue:appKey forKey:ARG_Akeeta_AppKey];
    if ([token isKindOfClass:[NSString class]]) {
        [dic setValue:token forKey:ARG_Akeeta_AccessToken];
    }

    //按key的首字母排序
    NSArray * newArray =  [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
    }];

    NSString * sortStr = @"";
    for (int i =0 ;i<newArray.count; i++) {
        id value = dic[newArray[i]];
        NSString *key = newArray[i];
        if ([value isKindOfClass:[NSString class]]) {
            NSString *temp = value;
            if (temp.length>0) {
                sortStr = [sortStr stringByAppendingFormat:@"%@", [NSString stringWithFormat:@"%@=%@&",key,value]];
            }
        }else if([value isKindOfClass:[NSDictionary class]]) {
            sortStr = [sortStr stringByAppendingFormat:@"%@", [NSString stringWithFormat:@"%@=%@&",key,[self objToJSONString:value]]];
        }else if([value isKindOfClass:[NSArray class]]) {
            sortStr = [sortStr stringByAppendingFormat:@"%@", [NSString stringWithFormat:@"%@=%@&",key,[self objToJSONString:value]]];
        }else{
            sortStr = [sortStr stringByAppendingFormat:@"%@", [NSString stringWithFormat:@"%@=%@&",key,[NSString stringWithFormat:@"%@",value]]];
        }
        //        sortStr = [sortStr stringByAppendingFormat:@"%@=%@&",newArray[i],dic[newArray[i]]];
    }

    //拼接appSecret 然后md5
    sortStr =[[NSString stringWithFormat:@"%@%@",sortStr,appsecret] MD5Digest]; //

    NSMutableDictionary * encodeParamDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    // 添加上签名
    [encodeParamDic setValue:sortStr forKey:ARG_Akeeta_Sign];//sign部分需要排序和MD5加密
    return encodeParamDic;
}

- (NSString *)objToJSONString:(id)obj {
    NSError *error = nil;
    NSString *jsonString;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:kNilOptions error:&error];
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

@end
